package com.gdepri.mqtt.subscriber;

import com.gdepri.mqtt.config.Config;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

//@Component
//用的是org.eclipse.paho.client.mqttv3.*;
public class SubscribeSampleV2 {


    @Autowired
    private Config config;

    @PostConstruct
    public  void Main() throws InterruptedException {
        System.out.println("SubscribeSampleV2已经被注入:"+config);
        String broker = config.getSubscribeBroker();
        String topic = config.getSubscribeTopic();
        String username = config.getSubscribeUsername();
        String password = config.getSubscribePassword();
        String clientid = config.getSubscribeClientId();
        int qos = 2;

        try {
            System.out.println("订阅者开始订阅");
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 设置连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            // 设置回调
            client.setCallback(new MqttCallback() {

                public void connectionLost(Throwable cause) {
                    System.out.println("@@@-------------connectionLost");
                    System.out.println("connectionLost: " + cause.getMessage());
                }

                public void messageArrived(String topic, MqttMessage message) {
                    System.out.println("@@@-------------messageArrived");
                    System.out.println("topic: " + topic);
                    System.out.println("Qos: " + message.getQos());
                    System.out.println("message content: " + new String(message.getPayload()));

                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("@@@-------------deliveryComplete");
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }
            });
            System.out.println("@_____end");
            client.connect(options);
            client.subscribe(topic, qos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
